<?php

/**
 * qMySQLFactory is factory class for MySQL database connection. 
 */
class qMySQLFactory
{

    /** Array containing all active connections to database. */
    private static $links = array();

    /**
     * Connect is most useful function of qMySQLFactory. It creates connection to specified MySQL server and - if $db is specified - also selects database. Uses qMySQLConnection.
     * @param string $host database host
     * @param string $user database username
     * @param string $pass database password
     * @param string $db database to select, optional
     * @return Numerical connection identifier to be passed to other qMySQLFactory functions. 
     */
    public static function Connect($host, $user, $pass, $db = null)
    {
        // connect to MySQL server
        qLogger::Log("Connecting to database: $user@$host using hashed password: " . md5($pass));
        $link = new qMySQLConnection($host, $user, $pass);

        // error occured, log
        if ($error = $link->Error())
        {
            qLogger::ErrorLog("Database connection: $user@$host using hashed password: " . md5($pass) . " failed.");
            unset($link);
            return false;
        }
        qLogger::Log("Connected using $user@$host using hashed password: " . md5($pass));

        // if database to select is specified, select it
        if ($db != null)
        {
            $link->SelectDatabase($db);

            if ($error = $link->Error())
            {
                unset($link);
                return false;
            }
        }

        // add link to links and return it's index
        self::$links[] = $link;
        return array_search($link, self::$links);
    }

    /**
     * Closes active connection.
     * @param int $linkid connection identifier.
     * @return boolean
     */
    public static function Close($linkid)
    {
        // if there is no connection with such identifier, log error
        if (!array_key_exists($linkid, self::$links))
        {
            qLogger::ErrorLog("Trying to close unexisting connection with id $linkid.");
            return false;
        }

        // disconnect
        qLogger::Log("Closing connection with id $linkid");
        self::$links[$linkid]->Disconnect();

        // error occured (huh? error when calling disconnect function? i do not believe in that), log it
        if ($error = self::$links[$linkid]->Error())
        {
            qLogger::ErrorLog("Error closing connection: $error.");
            return false;
        }

        // delete link from internal array
        unset(self::$links[$linkid]);
        return true;
    }

    /**
     * Returns connection object with identifier $id.
     * @param int $id connection identifier
     * @return qMySQLConnection
     */
    public static function GetLink($id)
    {
        return self::$links[$id];
    }
}